/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.swing.swixml.library;

import static nemos.swing.swixml.SwixmlMessage.BORDER_PARAMETERS_INVALID;

import javax.swing.border.Border;

import nemos.swing.IBorderFactory;
import nemos.util.log.NemosLogger;
import nemos.util.osgi.ServiceHashMap;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.swixml.ConverterLibrary;
import org.swixml.Localizer;
import org.swixml.converters.BorderConverter;

/**
 * BorderServiceConverter : The SwiXML converter for OSGi borders.
 * 
 * <p>
 * This component converts a string into a {@link Border}, using the registered
 * {@link IBorderFactory} services.
 * </p>
 * 
 * @author Romain DUBOIS
 */
@Component(immediate = true)
public class BorderServiceConverter extends BorderConverter {

    /** The border factories */
    @Reference(name = "factory", referenceInterface = IBorderFactory.class, cardinality = ReferenceCardinality.MANDATORY_MULTIPLE)
    private ServiceHashMap<IBorderFactory> mFactories;

    /** The logger */
    private NemosLogger mLogger;

    /**
     * Constructor.
     */
    public BorderServiceConverter() {
        super();
    }

    /**
     * Start the component
     * 
     * @param pContext
     *            The bundle context
     */
    @Activate
    public void start(final BundleContext pContext) {
        mLogger = new NemosLogger(getClass());
        ConverterLibrary.getInstance().register(this);
        mFactories = new ServiceHashMap<IBorderFactory>(IBorderFactory.BORDER_TYPE, pContext);
    }

    /**
     * Stop the component.
     */
    @Deactivate
    public void stop() {
        ConverterLibrary.getInstance().register(new BorderConverter());
        mFactories.clear();
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.swixml.converters.BorderConverter#convert(java.lang.Class,
     *      java.lang.String, org.swixml.Localizer)
     */
    @Override
    protected Border convert(final Class<?> type, final String borderString,
            final Localizer localizer) {

        // Find border type and parameters
        String lType = borderString;
        String lParams = null;
        final int lIndex = borderString.indexOf('(');
        if (lIndex != -1) {
            lType = borderString.substring(0, lIndex);

            // Check last char is the right parenthesis
            if (borderString.endsWith(")")) { //$NON-NLS-1$
                lParams = borderString.substring(lIndex, borderString.length() - 1);
            } else {
                mLogger.warn(BORDER_PARAMETERS_INVALID, lType, borderString.substring(lIndex));
            }
        }

        // Try to create border
        Border lBorder = null;
        final IBorderFactory lFactory;
        synchronized (mFactories) {
            lFactory = mFactories.getService(lType);
        }
        if (lFactory != null) {
            if (lParams == null) {
                lBorder = lFactory.createBorder();
            } else {
                lBorder = lFactory.createBorder(lParams);
            }
        }

        // Check standard borders
        if (lBorder == null) {
            lBorder = super.convert(type, borderString, localizer);
        }
        return lBorder;
    }

    /**
     * Bind a new border factory.
     * 
     * @param pReference
     *            The service reference
     */
    public void bindFactory(final ServiceReference<IBorderFactory> pReference) {
        synchronized (mFactories) {
            mFactories.add(pReference);
        }
    }

    /**
     * Unbind a border factory.
     * 
     * @param pReference
     *            The service reference
     */
    public void unbindFactory(final ServiceReference<IBorderFactory> pReference) {
        synchronized (mFactories) {
            mFactories.remove(pReference);
        }
    }
}
